const BaseHandler = require('../base-handler');
const SystemServices = require('../../../constants').SystemServices;
const HTTP_VERBS = require('../../../constants').HTTP_VERBS;
const moment = require('moment');

class AssociatorListHandler extends BaseHandler {
    get pattern() {
        return "/associator/list/:type";
    }

    // 获取顾客列表
    doGET(request, response) {
        if (!request.session.user.authenticated) {
            response.json({
                success: false,
                error: '请登录系统后再调用此接口！'
            });
        } else {
            let startTime = moment().subtract(6, 'd').format('YYYY-MM-DD');
            let endTime = moment().format('YYYY-MM-DD');
            var { page, size, cmd, type, storeId } = request.query, params = { page, size, cmd, type, startTime, endTime, storeId: storeId || request.session.user.storeId };
            this.Controller.getAssociatorList(params, (result) => {
                if (result.error) {
                    return response.json({
                        success: false,
                        error: result.error
                    });
                }
                if (result && result.data) {
                    result.data.forEach((v) => {
                        v.createTimestamp = moment(v.createTimestamp).format('YYYY-MM-DD HH:mm:ss')
                    });
                }
                if (result.total > 300) {
                    result.total = 300;
                }
                response.json({
                    success: true,
                    result: result
                });
            });

        }
    }

    // 
    doPOST(request, response) {
        var data = request.body;
        data.storeId = request.session.user.storeId;
        this.Controller.createNewContact(data, (result) => {
            if (result.error) {
                return response.json({
                    success: false,
                    error: result.error
                });
            }
            response.json({
                success: true,
                result: result
            });

        });
    }

    setup() {
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
        this.registerVerb(HTTP_VERBS.POST, this.doPOST);
    }
}

module.exports = AssociatorListHandler;